package com.panshi.controller;

import com.google.code.kaptcha.Producer;
import com.panshi.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
@Controller

public class LoginController {


    @Autowired
    private Producer producer;

    @Autowired
    private CommonUtil commonUtil;


    @GetMapping("/login")
    public String login(){
        return "login/login";
    }

    @GetMapping("/login/register")
    public String loginPhone(){
        return "login/login_register";
    }

    @GetMapping("/login/pass")
    public String loginPass(){
        return "login/login_pass";
    }


    @PostMapping("/out")
    @ResponseBody
    public String out(HttpServletRequest request,HttpServletResponse response){
        log.info("退出登录...");

        Cookie[] cookies = request.getCookies();//获取cookie数组
        for (Cookie c : cookies   //遍历cookie
        ) {
            if (c.getName().equals("1b12ebc9bf976801fd564c64867366c5")) {
                Cookie cookie = new Cookie("1b12ebc9bf976801fd564c64867366c5", "");//删除前必须要new 一个valu为空；
                cookie.setPath("/");//路径要相同
                cookie.setMaxAge(0);//生命周期设置为0
                response.addCookie(cookie);
                return "ok";
            }
        }
        return "";
    }




    /**
     * 验证码功能
     * @param response
     * @param session
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //log.info("验证码已生成");
        // 将验证码存入session
        session.setAttribute("kaptcha", text);

        log.info("生成图形验证码："+text);
        // 将突图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            log.error("响应验证码失败:{}" ,e.getMessage());

        }
    }


}
